import rasterio
from os import listdir
import pymongo
from argparse import ArgumentParser

client = pymongo.MongoClient('192.168.0.12', 27117)
db = client.hntp
terrain_collection = db.terrain

parser = ArgumentParser('parse geotiff and save it to mongo geo db')
parser.add_argument('-s', '--source', help='Directory to get SRTM tiff files', required=True)
args = parser.parse_args()


def save_to_mongo(data):
    # db.terrain.createIndex( { location : "2dsphere" } )
    terrain_collection.insert_many(data)


def parse_file(file):
    f = rasterio.open(file)
    data = f.read(1)
    ds = {}
    index = 0
    for i, v in enumerate(data):
        for j, height in enumerate(v):
            coordinates = f.transform * (i, j)
            ds.append({'location': coordinates, 'z': height})
            if index >= 100000:
                save_to_mongo(ds)
                ds = {}
            print('coordinates: %s height: %d' % (coordinates, height))
    save_to_mongo(ds)


def main():
    source = args.source
    for file in listdir(source):
        parse_file(file)


if __name__ == '__main__':
    main()